<!-- 扫码弹框组件 -->
<template>
  <div v-if="visible" class="scanner-dialog-overlay" @click="handleOverlayClick">
    <div class="scanner-dialog" @click.stop>
      <div class="scanner-dialog-header">
        <h3>请使用扫码枪扫码</h3>
        <el-icon class="close-btn" @click="handleClose">
          <Close />
        </el-icon>
      </div>

      <div class="scanner-dialog-content" @click="handleContentClick">
        <!-- 扫码状态图标 -->
        <div class="status-icon">
          <div v-if="!isScanning && !scanValue" class="icon-waiting">
            <svg class="scanner-icon" viewBox="0 0 64 64" fill="none">
              <!-- 外框 -->
              <rect
                x="8"
                y="8"
                width="48"
                height="48"
                rx="4"
                stroke="currentColor"
                stroke-width="2"
                fill="none"
              />
              <!-- 左上角 -->
              <rect x="8" y="8" width="12" height="12" fill="currentColor" />
              <path
                d="M8 8 L20 8 L20 20 L8 20 Z"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
              />
              <!-- 右上角 -->
              <rect x="44" y="8" width="12" height="12" fill="currentColor" />
              <path
                d="M44 8 L56 8 L56 20 L44 20 Z"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
              />
              <!-- 左下角 -->
              <rect x="8" y="44" width="12" height="12" fill="currentColor" />
              <path
                d="M8 44 L20 44 L20 56 L8 56 Z"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
              />
              <!-- 右下角 -->
              <rect x="44" y="44" width="12" height="12" fill="currentColor" />
              <path
                d="M44 44 L56 44 L56 56 L44 56 Z"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
              />
              <!-- 中心扫描线 -->
              <rect x="22" y="28" width="20" height="2" fill="currentColor" opacity="0.6" />
              <rect x="26" y="30" width="12" height="1" fill="currentColor" opacity="0.4" />
            </svg>
          </div>
          <div v-if="isScanning && !scanValue" class="icon-scanning">
            <svg class="scanner-icon scanning-animation" viewBox="0 0 64 64" fill="none">
              <!-- 外框 -->
              <rect
                x="8"
                y="8"
                width="48"
                height="48"
                rx="4"
                stroke="currentColor"
                stroke-width="2"
                fill="none"
              />
              <!-- 左上角 -->
              <rect x="8" y="8" width="12" height="12" fill="currentColor" />
              <path
                d="M8 8 L20 8 L20 20 L8 20 Z"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
              />
              <!-- 右上角 -->
              <rect x="44" y="8" width="12" height="12" fill="currentColor" />
              <path
                d="M44 8 L56 8 L56 20 L44 20 Z"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
              />
              <!-- 左下角 -->
              <rect x="8" y="44" width="12" height="12" fill="currentColor" />
              <path
                d="M8 44 L20 44 L20 56 L8 56 Z"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
              />
              <!-- 右下角 -->
              <rect x="44" y="44" width="12" height="12" fill="currentColor" />
              <path
                d="M44 44 L56 44 L56 56 L44 56 Z"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
              />
              <!-- 动画扫描线 -->
              <rect x="22" y="28" width="20" height="2" fill="currentColor" opacity="0.8">
                <animate
                  attributeName="opacity"
                  values="0.3;1;0.3"
                  dur="1.5s"
                  repeatCount="indefinite"
                />
              </rect>
              <rect x="26" y="30" width="12" height="1" fill="currentColor" opacity="0.6">
                <animate
                  attributeName="opacity"
                  values="0.1;0.8;0.1"
                  dur="1.5s"
                  repeatCount="indefinite"
                />
              </rect>
            </svg>
          </div>
          <div v-if="scanValue" class="icon-success">
            <el-icon class="success-icon">
              <CircleCheckFilled />
            </el-icon>
          </div>
        </div>

        <!-- 状态文本 -->
        <div class="status-text">
          <h3 v-if="!isScanning && !scanValue">等待扫码</h3>
          <h3 v-if="isScanning && !scanValue">正在扫码...</h3>
          <h3 v-if="scanValue">扫码成功</h3>

          <p v-if="!isScanning && !scanValue" class="tip-text">请将扫码枪对准条码进行扫描</p>
          <p v-if="isScanning && !scanValue" class="tip-text">扫码中，请稍候...</p>
          <div v-if="scanValue" class="success-content">
            <p class="auto-submit">正在自动提交...</p>
          </div>
        </div>

        <!-- 隐藏的输入框，用于接收扫码数据 -->
        <input
          ref="scannerInput"
          v-model="scanValue"
          type="text"
          class="scanner-input"
          placeholder="等待扫码..."
          @keydown="handleKeyDown"
          @input="handleInput"
          @blur="handleInputBlur"
        />

        <div class="scanner-actions">
          <button class="cancel-btn" @click="handleClose">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { Loading, CircleCheckFilled, Close } from '@element-plus/icons-vue'

interface Props {
  visible: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'onScan', value: string): void
  (e: 'onCancel'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false
})

const emit = defineEmits<Emits>()

const scannerInput = ref<HTMLInputElement>()
const scanValue = ref('')
const isScanning = ref(false)
const scanBuffer = ref('')
const scanTimer = ref<NodeJS.Timeout | null>(null)
const focusTimer = ref<NodeJS.Timeout | null>(null)
const lastKeyPressTime = ref(0)

// 监听弹框显示状态
watch(
  () => props.visible,
  newVal => {
    if (newVal) {
      resetScanState()
      nextTick(() => {
        // 强制聚焦到输入框
        if (scannerInput.value) {
          scannerInput.value.focus()
          console.log('🔍 弹框打开，强制聚焦到输入框')
        }
        // 启动焦点检查定时器
        startFocusCheck()
      })
    } else {
      // 停止焦点检查定时器
      stopFocusCheck()
    }
  }
)

// 重置扫码状态
const resetScanState = () => {
  scanValue.value = ''
  isScanning.value = false
  scanBuffer.value = ''
  lastKeyPressTime.value = 0
  if (scanTimer.value) {
    clearTimeout(scanTimer.value)
    scanTimer.value = null
  }
}

// 启动焦点检查定时器
const startFocusCheck = () => {
  stopFocusCheck() // 先清除之前的定时器
  focusTimer.value = setInterval(() => {
    if (props.visible && scannerInput.value && document.activeElement !== scannerInput.value) {
      console.log('🔍 定时检查：焦点丢失，重新聚焦')
      scannerInput.value.focus()
    }
  }, 50) // 每50ms检查一次，更频繁
}

// 停止焦点检查定时器
const stopFocusCheck = () => {
  if (focusTimer.value) {
    clearInterval(focusTimer.value)
    focusTimer.value = null
  }
}

// 处理键盘按下事件
const handleKeyDown = (event: KeyboardEvent) => {
  // 检测扫码枪的快速输入模式
  if (event.key === 'Enter') {
    event.preventDefault()
    if (scanBuffer.value.trim()) {
      // 检查是否是扫码枪输入（快速连续输入）
      const timeDiff = Date.now() - lastKeyPressTime.value
      const bufferLength = scanBuffer.value.length

      // 扫码枪特征：长度大于8，最后按键时间间隔小于50ms，且包含数字或字母
      if (bufferLength > 8 && timeDiff < 50 && /^[A-Za-z0-9]+$/.test(scanBuffer.value)) {
        // 扫码枪输入：快速且长度足够
        scanValue.value = scanBuffer.value.trim()
        isScanning.value = false
        scanBuffer.value = ''
        console.log('🔍 扫码完成:', scanValue.value)

        // 扫码完成后直接提交，延迟一点时间让用户看到结果
        setTimeout(() => {
          emit('onScan', scanValue.value)
          emit('update:visible', false)
        }, 800)
      } else {
        // 普通键盘输入：清空缓冲区，不处理
        console.log(
          '🔍 检测到普通键盘输入，忽略 (长度:',
          bufferLength,
          '时间差:',
          timeDiff,
          '内容:',
          scanBuffer.value,
          ')'
        )
        scanBuffer.value = ''
        isScanning.value = false
      }
    }
  } else if (event.key.length === 1) {
    // 记录字符输入和时间
    const currentTime = Date.now()
    scanBuffer.value += event.key
    lastKeyPressTime.value = currentTime

    // 检测快速输入（扫码枪特征）
    if (!isScanning.value && scanBuffer.value.length > 3) {
      isScanning.value = true
    }

    // 重置定时器
    if (scanTimer.value) {
      clearTimeout(scanTimer.value)
    }

    scanTimer.value = setTimeout(() => {
      // 超时重置状态
      if (scanBuffer.value && !scanValue.value) {
        console.log('🔍 输入超时，重置状态')
        scanBuffer.value = ''
        isScanning.value = false
      }
    }, 1000)
  }
}

// 处理输入事件
const handleInput = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.value !== scanValue.value) {
    scanValue.value = target.value
  }
}

// 处理输入框失焦事件
const handleInputBlur = () => {
  // 如果弹框还在显示，立即重新聚焦到输入框
  if (props.visible && scannerInput.value) {
    setTimeout(() => {
      scannerInput.value?.focus()
    }, 0)
  }
}

// 处理取消
const handleClose = () => {
  emit('onCancel')
  emit('update:visible', false)
}

// 组件挂载时添加全局键盘监听
onMounted(() => {
  document.addEventListener('keydown', handleGlobalKeyDown)
})

// 组件卸载时移除全局键盘监听
onUnmounted(() => {
  document.removeEventListener('keydown', handleGlobalKeyDown)
  if (scanTimer.value) {
    clearTimeout(scanTimer.value)
  }
  stopFocusCheck()
})

// 全局键盘监听（当弹框显示时）
const handleGlobalKeyDown = (event: KeyboardEvent) => {
  if (props.visible && scannerInput.value) {
    // 如果焦点不在输入框上，立即重新聚焦
    if (document.activeElement !== scannerInput.value) {
      console.log('🔍 检测到键盘事件，重新聚焦到输入框')
      scannerInput.value.focus()
    }
  }
}

// 处理蒙版层点击事件
const handleOverlayClick = (event: Event) => {
  // 点击蒙版层时重新聚焦到输入框，不关闭弹框
  if (scannerInput.value) {
    scannerInput.value.focus()
    console.log('🔍 蒙版层被点击，重新聚焦到输入框')
  }
}

// 处理点击事件，防止焦点丢失
const handleContentClick = (event: Event) => {
  // 阻止事件冒泡，防止点击内容区域时失去焦点
  event.preventDefault()
  event.stopPropagation()

  // 确保焦点回到输入框
  if (scannerInput.value) {
    scannerInput.value.focus()
    console.log('🔍 内容区域被点击，重新聚焦到输入框')
  }
}
</script>

<style lang="scss" scoped>
.scanner-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.scanner-dialog {
  background: white;
  border-radius: 16px;
  width: 420px;
  max-width: 90vw;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  animation: slideIn 0.3s ease-out;
  overflow: hidden;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.scanner-dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  background: linear-gradient(135deg, #7c0a03 0%, #a00d06 100%);
  color: white;

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: white;
  }

  .close-btn {
    background: rgba(255, 255, 255, 0.1);
    border: none;
    cursor: pointer;
    color: white;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.2s;

    &:hover {
      background: rgba(255, 255, 255, 0.2);
      transform: scale(1.1);
    }
  }
}

.scanner-dialog-content {
  padding: 40px 24px;
  text-align: center;
  min-height: 360px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.status-icon {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;

  .icon-waiting,
  .icon-scanning,
  .icon-success {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 120px;
    height: 120px;
    border-radius: 50%;
    margin: 0 auto;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  }

  .icon-waiting {
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    border: 2px solid #0ea5e9;

    .scanner-icon {
      width: 60px;
      height: 60px;
      color: #0ea5e9;
    }
  }

  .icon-scanning {
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    border: 2px solid #f59e0b;

    .scanner-icon {
      width: 60px;
      height: 60px;
      color: #f59e0b;
    }

    .scanning-animation {
      animation: pulse 1.5s ease-in-out infinite;
    }
  }

  .icon-success {
    background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%);
    border: 2px solid #22c55e;

    .success-icon {
      font-size: 60px;
      color: #22c55e;
    }
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.7;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.status-text {
  margin-bottom: 24px;

  h3 {
    margin: 0 0 8px 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
  }

  .tip-text {
    margin: 0;
    font-size: 14px;
    color: #666;
    line-height: 1.5;
  }

  .success-content {
    .barcode-result {
      margin: 0 0 8px 0;
      font-size: 18px;
      font-weight: 600;
      color: #52c41a;
      background: #f6ffed;
      padding: 8px 16px;
      border-radius: 6px;
      border: 1px solid #b7eb8f;
      display: inline-block;
    }

    .auto-submit {
      margin: 0;
      font-size: 14px;
      color: #7c0a03;
      font-weight: 500;
    }
  }
}

.scanner-input {
  position: absolute;
  left: -9999px;
  top: -9999px;
  opacity: 0;
  pointer-events: none;
}

.scanner-actions {
  display: flex;
  justify-content: center;
  margin-top: 8px;

  .cancel-btn {
    padding: 12px 32px;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    border: 2px solid #d9d9d9;
    background: white;
    color: #666;
    min-width: 120px;

    &:hover {
      background: #f5f5f5;
      border-color: #bfbfbf;
      transform: translateY(-1px);
    }

    &:active {
      transform: translateY(0);
    }
  }
}
</style>
